package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Classname RegisterController
 * @Description NULL
 * @Date 2021/5/22 14:55
 * @Created by virus
 */
@RestController
@RequestMapping("user")
public class RegisterController {

    @Reference(check = false)
    private IKaptchaService iKaptchaService;

    @Reference(check = false)
    private IRegisterService iRegisterService;

    @RequestMapping("register")
    @Anoymous
    public ResponseData register(@RequestBody UserRegisterRequest userRegisterRequest, HttpServletRequest servletRequest) {
        // 获取验证码验证后的响应体
        String uuid = CookieUtil.getCookieValue(servletRequest, "kaptcha_uuid");
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        kaptchaCodeRequest.setCode(userRegisterRequest.getCaptcha());
        kaptchaCodeRequest.setUuid(uuid);
        KaptchaCodeResponse kaptchaCodeResponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if (!kaptchaCodeResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setErrorMsg(kaptchaCodeResponse.getMsg());
        }

        // 写入用户表和用户验证表
        userRegisterRequest.setUuid(uuid);
        UserRegisterResponse userRegisterResponse = iRegisterService.register(userRegisterRequest);
        if (userRegisterResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(userRegisterResponse);
        }
        return new ResponseUtil<>().setErrorMsg(userRegisterResponse.getMsg());
    }
}
